package com.blinddate.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.blinddate.context.BaseContext;
import com.blinddate.mapper.GoodsTypeMapper;
import com.blinddate.mapper.OrdersMapper;
import com.blinddate.mapper.UserMapper;
import com.blinddate.pojo.dto.OrdersPaymentDTO;
import com.blinddate.pojo.entity.GoodsType;
import com.blinddate.pojo.entity.Orders;
import com.blinddate.pojo.entity.User;
import com.blinddate.pojo.vo.OrderPaymentVO;
import com.blinddate.service.OrdersService;
import com.blinddate.utils.WeChatPayUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;

@Service
@Slf4j
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper,Orders> implements OrdersService{

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private UserMapper userMapper;


    @Autowired
    private GoodsTypeMapper goodsTypeMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Override
    public void paySuccess(String outTradeNo) {
//        根据订单号获取数据库中的订单信息
        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordersLambdaQueryWrapper.eq(Orders::getOutTradeNo,outTradeNo);
        Orders orders = ordersMapper.selectOne(ordersLambdaQueryWrapper);
        orders.setStatus(Orders.PAID);
        orders.setCheckoutTime(LocalDateTime.now());
//        更新订单信息
        int update = ordersMapper.updateById(orders);
        if (update==1){
//            获取商品的信息
            LambdaQueryWrapper<GoodsType> goodsTypeLambdaQueryWrapper = new LambdaQueryWrapper<>();
            goodsTypeLambdaQueryWrapper.eq(GoodsType::getId,orders.getGoodsId());
//            获得商品的属性
            GoodsType goodsType = goodsTypeMapper.selectOne(goodsTypeLambdaQueryWrapper);
            Boolean aBoolean = goodsToUserInf(goodsType);
            if (aBoolean){
                log.info("用户充值回调操作完全成功");
            }else{
                log.info("用户充值回调操作失败");
            }
        }
    }

    public Boolean goodsToUserInf(GoodsType goodsType){
        //获取用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.selectById(userId);
        if (goodsType.getType()==1){//绿卡会员判断
            if (user.getGreenStartTime()==null || user.getGreenEndTime()==null || LocalDateTime.now().isAfter(user.getGreenEndTime())){
                user.setGreenStartTime(LocalDateTime.now());
                user.setGreenEndTime(LocalDateTime.now().plusDays(goodsType.getDay()));
            }else {
                user.setGreenEndTime(user.getGreenEndTime().plusDays(goodsType.getDay()));
            }
        }else if (goodsType.getType()==2){//vip解锁判读
            if (user.getVipTimeStart()==null||user.getVipTimeEnd()==null||LocalDateTime.now().isAfter(user.getVipTimeEnd())){
                user.setVipTimeStart(LocalDateTime.now());
                user.setVipTimeEnd(LocalDateTime.now().plusDays(goodsType.getDay()));
            }else {
                user.setVipTimeEnd(user.getVipTimeEnd().plusDays(goodsType.getDay()));
            }
        }else if (goodsType.getType()==3){//线下展示判断
            if (user.getShowStartTime()==null ||user.getShowEndTime()==null || LocalDateTime.now().isAfter(user.getShowEndTime())){
                user.setShowStartTime(LocalDateTime.now());
                user.setShowEndTime(LocalDateTime.now().plusDays(goodsType.getType()));
            }else {//解锁次数判断
                user.setShowEndTime(user.getShowEndTime().plusDays(goodsType.getType()));
            }
        }else{
            user.setCount(goodsType.getCount());
        }
        int i = userMapper.updateById(user);
        return i==1;
    }

    private static final BigDecimal bigDecimal = new BigDecimal("100");



    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) {
        //获取 用户id
        Long currentId = BaseContext.getCurrentId();
        User user = userMapper.selectById(currentId);
        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordersLambdaQueryWrapper.eq(Orders::getOutTradeNo,ordersPaymentDTO.getOutTradeNo());
        //获取订单
        Orders orders = ordersMapper.selectOne(ordersLambdaQueryWrapper);
        try {
            log.info("支付信息{}",orders.toString());
            JSONObject pay = weChatPayUtil.pay(ordersPaymentDTO.getOutTradeNo(), new BigDecimal(orders.getTotal()).divide(bigDecimal, 2, BigDecimal.ROUND_HALF_UP), orders.getDescription(), user.getOpenId());
            if (pay.getString("code")!=null&&pay.getString("code").equals("ORDERPAID")){
                throw new RuntimeException("该订单已经支付");
            }
            OrderPaymentVO orderPaymentVO = pay.toJavaObject(OrderPaymentVO.class);
            orderPaymentVO.setPackageStr(pay.getString("package"));
            return orderPaymentVO;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public Long getCount(Integer day, Long shopId, Long goodsId) {
        Long ordersCount = ordersMapper.getCountOrders(day, shopId, goodsId);
        return ordersCount;
    }

    @Override
    public Long getAllCount(Integer day, Long goodsId) {
        Long allCountOrders = ordersMapper.getAllCountOrders(day, goodsId);
        return allCountOrders;
    }

    public Integer getMorTime(Long shopId){
        Integer mOrTime = ordersMapper.getMOrTime(shopId);
        if (mOrTime==null||mOrTime==0){
            return 0;
        }
        return mOrTime;
    }


}
